﻿(function () {

    layui.use(["layer", "jquery", "table", "form", "tree", "laydate", "dropdown"], function () {
        var layer = layui.layer;
        var $ = layui.jquery;
        var table = layui.table;
        var form = layui.form;
        var tree = layui.tree;
        var laydate = layui.laydate;
        var dropdown = layui.dropdown;
        var carousel = layui.carousel;

        $(document).ready(function () {
            $("#btnSearch").click(function () {
                reloadTable();
            });
        });

        var currentDate = moment().format("YYYY-MM-DD");
        if (moment().get("hours") < 15) {
            currentDate = moment().add(-1, "days").format("YYYY-MM-DD");
        }
        laydate.render({
            elem: '#txtSearchDate',
            value: currentDate,
            isInitValue: true,
            showBottom: false
        });

        tool.getOrderStatusArr().forEach(item => {
            var obj = { title: item["text"], id: item["value"] };
            var option = new Option(item["text"], item["value"]);
            $("#selSearchOrderStatus").append(option);
        });
        form.render("select");

        function reloadTable() {
            table.reloadData("OrderTable", {
                where: getTableQueryParam()
            });
        }

        table.render({
            elem: "#OrderTable",
            url: "/Order/List",
            height: "full-68", // (10 + 38 + 10 + 10)
            page: false,
            method: "POST",
            where: getTableQueryParam(),
            even: true,
            totalRow: true,
            parseData: function (res) {
                //console.log(res);
                return {
                    "code": res.Success == true ? 0 : -1,
                    "msg": res.Msg,
                    "count": res.Count,
                    "data": res.Data,
                    "totalRow": {
                        "count": res.Data.length
                    }
                };
            },
            cols: [[
                {
                    type: 'numbers', title: 'No.', width: 60, fixed: 'center'
                    , totalRow: '{{= d.TOTAL_ROW.count }}'
                }
                , {
                    field: "OrderNo", width: 200, align: "center", title: "订单号"
                }
                , { field: "ProductName", width: 90, align: "center", title: "产品名称" }
                , { field: "Buyer", width: 80, align: "center", title: "买家" }
                , {
                    field: "Amount", width: 100, align: "center", title: "金额",
                    totalRow: true, templet: function (d) {
                        return '<span style="color: #a233c6;">' + d["Amount"] + '</span>';
                    }
                }
                , { field: "Seller", width: 80, align: "center", title: "卖家" }
                , { field: "Time", width: 160, align: "center", title: "下单时间" }
                , {
                    field: "State", width: 80, align: "center", title: "状态", templet: function (d) {
                        //console.log(d);
                        var text = tool.getOrderStatusTextByValue(d.State);
                        var color = "";
                        if (d.State == tool.EOrderStatus.Unpaid) {
                            color = "color: red;";
                        } else if (d.State == tool.EOrderStatus.Paid
                            || d.State == tool.EOrderStatus.RecvPayment) {
                            color = "color: green;";
                        } else if (d.State == tool.EOrderStatus.Fetch) {
                            color = "color: #cbc90a;";
                        }
                        return '<span style="' + color + '">' + text + '</span>';
                    }
                }
                , {
                    field: "Visible", width: 80, align: "center", title: "发布"
                    , templet: function (d) {
                        if (d["Visible"] == 0) {
                            return '<span style="color: #ffb800;">未发布</span>';
                        } else {
                            return "已发布";
                        }
                    }
                }
                , { align: "center", title: "操作", fixed: "right", minWidth: 180, toolbar: "#ToolBar-OrderTable" }
            ]]
        });

        table.on("tool(filter-table-order)", function (obj) {
            var layEvent = obj.event;
            if (layEvent == "viewPaymentInfo") {
                onViewPaymentInfoHandle(obj);
            } else if (layEvent == "updateOrderInfo") {
                onUpdateOrderInfoHandle(obj);
            }
        });

        function getTableQueryParam() {
            return {
                OrderNo: $("#txtSearchOrderNo").val().trim(),
                Date: $("#txtSearchDate").val().trim(),
                Buyer: $("#txtSearchBuyer").val().trim(),
                Seller: $("#txtSearchSeller").val().trim(),
                State: $("#selSearchOrderStatus").val()
            };
        }

        function onViewPaymentInfoHandle(obj) {
            var data = obj.data;
            var layEvent = obj.event;
            var tr = obj.tr;

            layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.1, '#000'],
                skin: 'layui-layer-molv',
                offset: "0%",
                area: ["350px", "100%"],
                resize: false,
                content: '<div id="ViewPaymentInfoDlg2">' + $("#ViewPaymentInfoDlg").html() + '</div>'
            });

            if (data.PaymentVoucherImagePath != "") {
                var el = $("#ViewPaymentInfoDlg2 > div").eq(0);
                var el2 = $("#ViewPaymentInfoDlg2 > div > div").eq(0);
                var width = $("#ViewPaymentInfoDlg2").parent().width();
                var height = $("#ViewPaymentInfoDlg2").parent().height();
                var arr = data.PaymentVoucherImagePath.split(",");
                var html = '';
                var host = tool.getMTCPPhoneClientWebAddress();
                arr.forEach(item => {
                    var src = host + item;
                    html += '<div><img style="width: ' + width + 'px; height: ' + height + 'px;" src=" ' + src + '"></div>';

                });
                el2.append(html);

                if (arr != null && arr.length > 0) {
                    carousel.render({
                        elem: el,
                        width: width + "px",
                        height: height + "px",
                        interval: 3000
                    });
                }
            }
        }

        function onUpdateOrderInfoHandle(obj) {
            var data = obj.data;
            var layEvent = obj.event;
            var tr = obj.tr;
            var orderId = data["Id"];
            var buyerUserId = data["BuyerUserId"];
            var sellerUserId = data["SellerUserId"];

            var layId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.1, '#000'],
                skin: 'layui-layer-molv',
                offset: ["10%"],
                resize: false,
                content: '<div id="UpdateOrderInfo2">' + $("#UpdateOrderInfo").html() + '</div>'
            });

            form.render($("#txt-UpdateOrderInfo-Amount"));

            $("#lb-UpdateOrderInfo-BuyerName").text(data["Buyer"]);
            $("#lb-UpdateOrderInfo-SellerName").text(data["Seller"]);
            $("#txt-UpdateOrderInfo-Amount").val(data["Amount"]);

            $("#btn-UpdateOrderInfo-SearchBuyer").click(onUpdateOrderInfoSearchBuyerBtnClick);
            $("#btn-UpdateOrderInfo-SearchSeller").click(onUpdateOrderInfoSearchSellerBtnClick);

            $("#btn-UpdateOrderInfo-OK").click(onUpdateOrderInfoOKBtnClick);

            function onUpdateOrderInfoSearchBuyerBtnClick() {
                showSearchUserDlg(function (userId, text) {
                    buyerUserId = userId;
                    $("#lb-UpdateOrderInfo-BuyerName").text(text);
                });
            }

            function onUpdateOrderInfoSearchSellerBtnClick() {
                showSearchUserDlg(function (userId, text) {
                    sellerUserId = userId;
                    $("#lb-UpdateOrderInfo-SellerName").text(text);
                });
            }

            var selectedUserId = 0;
            var selectedUserName = "";
            function showSearchUserDlg(fn) {
                var layId2 = layer.open({
                    type: 1,
                    title: "满堂创品",
                    shade: [0.1, '#000'],
                    skin: 'layui-layer-molv',
                    offset: ["10%"],
                    resize: false,
                    content: '<div id="SelectUserDlg2">' + $("#SelectUserDlg").html() + '</div>'
                });

                var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                    { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                $.ajax("/User/List2", {
                    method: "POST",
                    complete: function (jqXHR, textStatus) {
                        layer.close(loadingIndex);
                    },
                    success: function (data, textStatus, jqXHR) {
                        $("#txt-SelectUserDlg-Name").focus();
                        if (data.Success == true) {
                            layer.msg(addStyle("加载会员数据成功！"), { time: 1 * 1000 });
                            handleData(data.Data)
                        } else {
                            layer.msg(addStyle("加载会员数据失败: " + data.Msg));
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.msg(addStyle("系统错误，请联系管理员！"),
                            { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                    }
                });

                function handleData(data) {
                    var html = '';
                    data.forEach(item => {
                        html += '<li tagPhone="' + item["Phone"] + '" tagUserId="' + item["Id"] + '" title="' + item["Phone"] + '">' + item["Name"] + '</li>';
                    });
                    $("#SelectUserDlg2 ul").eq(0).append(html);
                    $("#SelectUserDlg2 ul li").hover(function () {
                        var el = $(this);
                        $(this).addClass("list-item-highlight");
                    }, function () {
                        $(this).removeClass("list-item-highlight");
                    }).click(onListItemClick);
                    $("#txt-SelectUserDlg-Name").bind("input propertychange", onSelectUserDlgNameChange);
                    $("#btn-SelectUserDlg-OK").click(onSelectUserDlgOkBtnClick);
                }

                function onListItemClick() {
                    var el = $(this);
                    var text = el.text() + "(" + el.attr("tagPhone") + ")";
                    $("#lb-SelectUserDlg-Result").text(text);
                    selectedUserId = el.attr("tagUserId");
                    selectedUserName = el.text();
                }

                function onSelectUserDlgNameChange() {
                    var els = $("#SelectUserDlg2 ul li");
                    for (var i = 0; i < els.length; i++) {
                        var item = els.eq(i);
                        var text = item.text();
                        if (text.indexOf($("#txt-SelectUserDlg-Name").val()) > -1) {
                            item.show();
                        } else {
                            item.hide();
                        }
                    }
                }

                function onSelectUserDlgOkBtnClick() {
                    if (selectedUserId == 0) {
                        layer.msg(addStyle("请先选择会员！"), { time: 1 * 1000 });
                    } else {
                        layer.close(layId2);
                        if (fn != null) {
                            fn(selectedUserId, selectedUserName);
                        }
                    }
                }
            }

            function onUpdateOrderInfoOKBtnClick() {
                var val = $("#txt-UpdateOrderInfo-Amount").val();
                var amount = parseFloat(val, 10);
                if (val >= 1000 && val <= 15000) {
                    var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                        { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                    $.ajax("/Order/UpdateOrder", {
                        method: "POST",
                        data: {
                            OrderId: orderId,
                            BuyerUserId: buyerUserId,
                            SellerUserId: sellerUserId,
                            Amount: val
                        },
                        complete: function (jqXHR, textStatus) {
                            layer.close(loadingIndex);
                        },
                        success: function (data, textStatus, jqXHR) {
                            if (data.Success == true) {
                                layer.close(layId);
                                layer.msg(addStyle("更新订单成功！"),
                                    {
                                        icon: 1, time: 1 * 1000, offset: "20%", end: function () {
                                            reloadTable();
                                        }
                                    });
                            } else {
                                layer.msg(addStyle("更新订单失败: " + data.Msg),
                                    { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                                );
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.msg(addStyle("系统错误，请联系管理员！"),
                                { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                        }
                    });
                } else {
                    layer.msg(addStyle("请输入正确格式的订单金额!"),
                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                    );
                }
            }
        }

        function addStyle(str) {
            return '<span style="font-size: 16px;">' + str + '</span>';
        }
    });

})();